package com.dhemery.mack.actions;

import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IWorkbenchPage;

import com.dhemery.mack.adapters.ImageDescriptorSource;

public abstract class ExplorerViewAction extends Action implements ISelectionChangedListener {
	protected abstract void execute(IWorkbenchPage page, IAdapterFactory factory, Object[] selectedObjects);
	protected abstract boolean isSelected(Object[] selectedObjects);

	private final IAdapterFactory factory;
	private final IWorkbenchPage page;
	private Object[] selectedObjects;

	public ExplorerViewAction(String name, String id, String imagePath,
			IWorkbenchPage page, TreeViewer viewer,
			IAdapterFactory factory, ImageDescriptorSource imageDescriptorSource) {
		super(name);
		setId(id);
		setActionDefinitionId(id);
		setImageDescriptor(imageDescriptorSource.getImageDescriptor(imagePath));
		this.factory = factory;
		this.page = page;
		setEnabled(false);
		viewer.addSelectionChangedListener(this);
	}

	public IAdapterFactory getFactory() {
		return factory;
	}

	public IWorkbenchPage getPage() {
		return page;
	}

	@Override
	public void run() {
		execute(page, factory, selectedObjects);
	}
	
	public void selectionChanged(SelectionChangedEvent event) {
		StructuredSelection selection = (StructuredSelection)event.getSelection(); 
		selectedObjects = selection.toArray();
		setEnabled(isSelected(selectedObjects));
	}
}